/**
 * 
 */
package com.p2p.front.tender;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import com.p2p.base.constents.InnerAccountConsts;
import com.p2p.base.exception.BizException;
import com.p2p.base.model.Money;
import com.p2p.base.util.DateUtil;
import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.dal.model.LoanVariation;
import com.p2p.front.dal.model.Tender;
import com.p2p.front.dal.model.User;
import com.p2p.front.enums.TenderStatus;
import com.p2p.trans.client.enums.FreezeBalanceTypeEnum;
import com.p2p.trans.client.enums.SubTransCodeEnum;
import com.p2p.trans.client.enums.TransCodeEnum;
import com.p2p.trans.client.model.TransInfo;
import com.p2p.trans.client.result.AccountTransResult;

/**
 * @author ruiqi
 *
 */
@Service("normalLoanTender")
public class NormalLoanTender extends AbstractTenderBiz {

	/* (non-Javadoc)
	 * @see com.p2p.user.tender.AbstractTenderBiz#doUserTrans(java.lang.String, com.p2p.base.model.Money, java.lang.String)
	 */
	@Override
	protected void doUserTrans(String accountNo, Money amount, String bizNo) {
		TransInfo transInfo = new TransInfo();
		transInfo.setTransAccountIn(accountNo);
		transInfo.setTransAmount(amount);
		transInfo.setFreezeType(FreezeBalanceTypeEnum.FREEZE_FOR_TENDER);
		AccountTransResult transResult = this.remoteAccountTransFacade.doFreeze(transInfo);
		if(!transResult.isSuccess()){
			throw new BizException(transResult.getResultCode());
		}
	}

	@Override
	protected void afterTenderProcessing(Tender tender) {
		super.afterTenderProcessing(tender);
	}
	
	@Override
	protected void doExtraTenderFullBiz(List<Tender> tenderList, LoanInfo loanInfo) {
		Date fullTime = new Date();
		for(Tender tender:tenderList){
			TransInfo transInfo = new TransInfo();
			transInfo.setTransAccountOut(tender.getUserAccount());
			transInfo.setTransAmount(tender.getAmount());
			transInfo.setFreezeType(FreezeBalanceTypeEnum.FREEZE_FOR_TENDER);
			transInfo.setTransMemo("投标");
			transInfo.setTransCode(TransCodeEnum.TXCODE_TRANSFER);
			transInfo.setSubTransCode(SubTransCodeEnum.SUB_TRANSFER_TENDER);
			AccountTransResult transResult = this.remoteAccountTransFacade.doUnFreezeAndTransfer(transInfo);
			if(transResult.isSuccess()){
				tender.setStatus(TenderStatus.REAPYING.getCode());
				tender.setLoanTime(fullTime);
				this.tenderService.updateTenderStatusForLoanFull(tender.getTid(), tender.getStatus(),tender.getLoanTime());
				this.tenderReturnService.create(tender, loanInfo);
				
			}else{
				logger.equals("trans error for tender tid:"+tender.getTid());
			}
		}
		
	}

	@Override
	public void doLoanMoney(LoanVariation loanStatus, LoanInfo loanInfo) {
		
		TransInfo transInfo = new TransInfo();
		transInfo.setTransCode(TransCodeEnum.TXCODE_TRANSFER);
		transInfo.setSubTransCode(SubTransCodeEnum.SUB_TRANSFER_LOAN);
		Long uid = loanInfo.getUid();
		User user = userService.findById(String.valueOf(uid));
		//普通标转账到借款人账户
		transInfo.setTransAccountIn(user.getAccountNo());
		transInfo.setTransAmount(loanStatus.getTenderAmount());
		transInfo.setTransMemo("放款");
		AccountTransResult result = this.remoteAccountTransFacade.transfer(transInfo);
		if(!result.isSuccess()){
			logger.error("普通标标归集账务错误:code="+result.getResultCode()+"loanId="+loanInfo.getLid());
			return;
		}
		super.doCreatLoanRepay(loanStatus, loanInfo);
		
		double feeRate = loanInfo.getFeeRate();
		double feeRateValue = feeRate/100;
		
		Long feeCent = new Double(loanStatus.getTenderAmount().getCent()*feeRateValue).longValue();
		TransInfo transInfo2 = new TransInfo();
		transInfo2.setTransAccountOut(user.getAccountNo());
		transInfo2.setTransAccountIn(InnerAccountConsts.innerTenderAccountNo);
		transInfo2.setTransAmount(new Money(feeCent));
		transInfo2.setTransMemo("服务费");
		AccountTransResult result2 = this.remoteAccountTransFacade.transfer(transInfo2);
		if(!result2.isSuccess()){
			logger.error("普通标标收取服务费失败:code="+result.getResultCode()+"loanId="+loanInfo.getLid());
			return;
		}
		
	}

	@Override
	protected void doExtraLoanFullBiz(LoanVariation loanStatus,
			LoanInfo loanInfo) {

		// 普通标满标更新借款起止时间
		int deadLine = loanInfo.getDeadline();
		Date now = new Date();
		Date date = DateUtil.addMonth(now, deadLine);

		this.loanInfoService.updateBeginEndTime(loanStatus.getLoanId(),now, date);
		
		if (loanInfo.getIsOkout() != null && loanInfo.getIsOkout() == 1) {
			this.doLoanMoney(loanStatus, loanInfo);
		}
	}

	@Override
	public void doTenderExpiredBiz(LoanVariation LoanVariation) {
		boolean bool = this.loanVariationService.updateStatusForTimeExpired(LoanVariation.getLoanId());
		
		if(!bool){
			return;
		}
		List<Tender> tenderList = this.tenderService.findSuccesedByLoanId(LoanVariation.getLoanId());
		//循环解冻
		for(Tender tender:tenderList){
			TransInfo transInfo = new TransInfo();
			transInfo.setTransAccountOut(tender.getUserAccount());
			transInfo.setTransAmount(tender.getAmount());
			transInfo.setFreezeType(FreezeBalanceTypeEnum.FREEZE_FOR_TENDER);
			transInfo.setTransMemo("流标解冻");
			AccountTransResult transResult = this.remoteAccountTransFacade.doUnFreeze(transInfo);
			if(!transResult.isSuccess()){
				throw new BizException(transResult.getResultCode());
			}else{
				this.tenderService.updateTenderStatus(tender.getTid(), 3);
			}
		}
	}
	
}
